#include "AudioOutput.h"
#include <QDebug>

AudioOutput::AudioOutput(QObject* parent)
    : QObject(parent), m_audioOutput(nullptr), m_outputDevice(nullptr) {
    // 配置音频格式 (必须和 AudioInput 的一致)
    QAudioFormat format;
    format.setSampleRate(16000);
    format.setChannelCount(1);
    format.setSampleSize(16);
    format.setCodec("audio/pcm");
    format.setByteOrder(QAudioFormat::LittleEndian);
    format.setSampleType(QAudioFormat::SignedInt);

    QAudioDeviceInfo info = QAudioDeviceInfo::defaultOutputDevice();
    if (!info.isFormatSupported(format)) {
        qWarning() << "默认输出设备不支持指定格式，使用最接近的格式";
        format = info.nearestFormat(format);
    }

    m_audioOutput = new QAudioOutput(info, format, this);

    m_audioOutput->setBufferSize(3200);
}

AudioOutput::~AudioOutput() {
    stop();
}

void AudioOutput::start() {
    if (!m_audioOutput) return;
    m_outputDevice = m_audioOutput->start();
}

void AudioOutput::stop() {
    if (m_audioOutput) {
        m_audioOutput->stop();
        m_outputDevice = nullptr;
    }
}

void AudioOutput::playData(const QByteArray& data) {
    if (m_outputDevice && !data.isEmpty()) {
        m_outputDevice->write(data);
    }
}
